import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import '../index.dart';

/// 内购工具类
class PurchaseManager {
  static final PurchaseManager _instance = PurchaseManager._internal();
  factory PurchaseManager() => _instance;
  PurchaseManager._internal();

  InAppPurchase? _iap;
  StreamSubscription<List<PurchaseDetails>>? _subscription;
  List<ProductDetails> _products = [];

  bool _isInitialized = false;
  bool _isInitializing = false;
  bool _isRestoring = false;

  /// 用户状态更新回调
  VoidCallback? _onUserStateUpdated;

  /// 设置用户状态更新回调
  void setUserStateUpdateCallback(VoidCallback? callback) {
    _onUserStateUpdated = callback;
  }

  /// 订阅产品ID列表
  static const List<String> _subscriptionProductIds = [
    'com.lmmi.ios.vip.wk.9_99', // 一周订阅
    'com.lmmi.ios.vip.mo.19_99', // 一月订阅
    'com.lmmi.ios.vip.qtr.29_99', // 三月订阅
    'com.lmmi.ios.vip.ann.69_99', // 一年订阅
  ];

  /// 非消耗品产品ID列表
  static const List<String> _nonConsumableProductIds = [
    'com.lmmi.ios.prem.4_99', // Lmmi Pro
  ];

  /// 消耗品产品ID列表
  static const List<String> _consumableProductIds = [
    'com.lmmi.ios.prem.4_99', // 1x-Lmmi 图片
    'com.lmmi.ios.pri_pic.5x.14_99', // 5x-Lmmi 图片
    'com.lmmi.ios.pri_pic.10x.19_99', // 10x-Lmmi 图片
    'com.lmmi.ios.pri_pic.30x.49_99', // 30x-Lmmi 图片
    'com.lmmi.ios.pri_vid.1x.6_99', // 1x_Lmmi 视频
    'com.lmmi.ios.pri_vid.5x.19_99', // 5x_Lmmi 视频
    'com.lmmi.ios.pri_vid.10x.29_99', // 10x_Lmmi 视频
    'com.lmmi.ios.pri_vid.30x.79_99', // 30x_Lmmi 视频
  ];

  /// 获取所有产品ID
  List<String> get _allProductIds => [
    ..._subscriptionProductIds,
    ..._nonConsumableProductIds,
    ..._consumableProductIds,
  ];

  /// 初始化内购服务
  Future<bool> initialize() async {
    if (_isInitialized) return true;
    if (_isInitializing) {
      // 等待初始化完成
      int attempts = 0;
      while (_isInitializing && attempts < 50) {
        await Future.delayed(const Duration(milliseconds: 100));
        attempts++;
      }
      return _isInitialized;
    }

    _isInitializing = true;
    try {
      await _setupInAppPurchase();
      _isInitialized = true;
      debugPrint('内购服务初始化成功');
      return true;
    } catch (e) {
      debugPrint('内购服务初始化失败: $e');
      return false;
    } finally {
      _isInitializing = false;
    }
  }

  /// 设置内购服务
  Future<void> _setupInAppPurchase() async {
    _iap = InAppPurchase.instance;

    // 检查内购是否可用
    final bool isAvailable = await _iap!.isAvailable();
    if (!isAvailable) {
      throw Exception('内购服务不可用');
    }

    // 监听购买流
    _subscription = _iap!.purchaseStream.listen(
      _handlePurchaseUpdates,
      onDone: () => _subscription?.cancel(),
      onError: (error) => debugPrint('购买流错误: $error'),
    );

    // 加载产品信息
    await _loadProducts();
  }

  /// 加载产品信息
  Future<void> _loadProducts() async {
    try {
      final ProductDetailsResponse response = await _iap!.queryProductDetails(
        _allProductIds.toSet(),
      );

      if (response.error != null) {
        throw Exception('查询产品详情失败: ${response.error}');
      }

      _products = response.productDetails;
      debugPrint('成功加载 ${_products.length} 个产品');

      // 打印产品信息用于调试
      for (final product in _products) {
        debugPrint('产品: ${product.id} - ${product.title} - ${product.price}');
      }
    } catch (e) {
      debugPrint('加载产品信息失败: $e');
      rethrow;
    }
  }

  /// 处理购买更新
  void _handlePurchaseUpdates(List<PurchaseDetails> purchases) async {
    for (final purchase in purchases) {
      switch (purchase.status) {
        case PurchaseStatus.purchased:
          await _handleSuccessfulPurchase(purchase, false);
          break;
        case PurchaseStatus.restored:
          await _handleSuccessfulPurchase(purchase, true);
          break;
        case PurchaseStatus.error:
          debugPrint('购买错误: ${purchase.error?.message}');
          await _iap!.completePurchase(purchase);
          break;
        case PurchaseStatus.canceled:
          debugPrint('购买取消: ${purchase.productID}');
          await _iap!.completePurchase(purchase);
          break;
        case PurchaseStatus.pending:
          debugPrint('购买待处理: ${purchase.productID}');
          break;
      }
    }
  }

  /// 处理成功的购买
  Future<void> _handleSuccessfulPurchase(
    PurchaseDetails purchase,
    bool isRestore,
  ) async {
    try {
      final productId = purchase.productID;
      debugPrint('处理${isRestore ? "恢复" : "购买"}成功: $productId');

      // 如果是订阅产品，更新用户VIP状态
      if (_subscriptionProductIds.contains(productId)) {
        await _processSubscriptionPurchase(productId, isRestore);
      }
      // 如果是非消耗品，处理相应逻辑
      else if (_nonConsumableProductIds.contains(productId)) {
        await _processNonConsumablePurchase(productId, isRestore);
      }
      // 如果是消耗品，处理相应逻辑
      else if (_consumableProductIds.contains(productId)) {
        await _processConsumablePurchase(productId, isRestore);
      }

      // 完成购买
      await _iap!.completePurchase(purchase);
    } catch (e) {
      debugPrint('处理购买完成时出错: $e');
      await _iap!.completePurchase(purchase);
    }
  }

  /// 处理订阅购买
  Future<void> _processSubscriptionPurchase(
    String productId,
    bool isRestore,
  ) async {
    try {
      // 更新用户VIP状态
      final success = await UserService.updateVip();

      if (success) {
        debugPrint('用户VIP状态更新成功');

        // 保存订阅信息到本地存储
        await _saveSubscriptionInfo(productId);

        // 通知用户状态更新
        _onUserStateUpdated?.call();
      } else {
        debugPrint('用户VIP状态更新失败');
      }
    } catch (e) {
      debugPrint('处理订阅购买时出错: $e');
    }
  }

  /// 处理非消耗品购买
  Future<void> _processNonConsumablePurchase(
    String productId,
    bool isRestore,
  ) async {
    try {
      // 处理Lmmi Pro购买
      if (productId == 'com.lmmi.ios.prem.4_99') {
        final success = await UserService.updateVip();
        if (success) {
          debugPrint('Lmmi Pro购买成功，用户VIP状态更新');
          // 通知用户状态更新
          _onUserStateUpdated?.call();
        }
      }
    } catch (e) {
      debugPrint('处理非消耗品购买时出错: $e');
    }
  }

  /// 处理消耗品购买
  Future<void> _processConsumablePurchase(
    String productId,
    bool isRestore,
  ) async {
    try {
      // 这里可以处理消耗品的逻辑，比如增加用户的某些资源
      debugPrint('消耗品购买成功: $productId');
    } catch (e) {
      debugPrint('处理消耗品购买时出错: $e');
    }
  }

  /// 保存订阅信息
  Future<void> _saveSubscriptionInfo(String productId) async {
    try {
      final now = DateTime.now();
      DateTime expiryDate;

      // 根据产品ID确定过期时间
      if (productId.contains('wk')) {
        expiryDate = now.add(const Duration(days: 7)); // 一周
      } else if (productId.contains('mo')) {
        expiryDate = now.add(const Duration(days: 30)); // 一月
      } else if (productId.contains('qtr')) {
        expiryDate = now.add(const Duration(days: 90)); // 三月
      } else if (productId.contains('ann')) {
        expiryDate = now.add(const Duration(days: 365)); // 一年
      } else {
        expiryDate = now.add(const Duration(days: 30)); // 默认一月
      }

      // 使用Hive存储订阅信息
      await HiveUtil.put('subscription', 'product_id', productId);
      await HiveUtil.put(
        'subscription',
        'expiry_date',
        expiryDate.toIso8601String(),
      );
      await HiveUtil.put(
        'subscription',
        'purchase_date',
        now.toIso8601String(),
      );

      debugPrint('订阅信息保存成功，过期时间: $expiryDate');
    } catch (e) {
      debugPrint('保存订阅信息失败: $e');
    }
  }

  /// 购买产品
  Future<bool> buyProduct(String productId) async {
    try {
      if (!_isInitialized) {
        final initialized = await initialize();
        if (!initialized) {
          debugPrint('内购服务未初始化');
          return false;
        }
      }

      // 查找产品
      final product = _products.firstWhere(
        (p) => p.id == productId,
        orElse: () => throw Exception('产品不存在: $productId'),
      );

      final purchaseParam = PurchaseParam(productDetails: product);

      // 根据产品类型选择购买方式
      if (_subscriptionProductIds.contains(productId) ||
          _nonConsumableProductIds.contains(productId)) {
        await _iap!.buyNonConsumable(purchaseParam: purchaseParam);
      } else {
        await _iap!.buyConsumable(purchaseParam: purchaseParam);
      }

      debugPrint('发起购买请求: $productId');
      return true;
    } catch (e) {
      debugPrint('购买产品失败: $e');
      return false;
    }
  }

  /// 恢复购买
  Future<bool> restorePurchases() async {
    if (_isRestoring) {
      debugPrint('正在恢复购买中...');
      return false;
    }

    _isRestoring = true;
    try {
      if (!_isInitialized) {
        final initialized = await initialize();
        if (!initialized) {
          debugPrint('内购服务未初始化');
          return false;
        }
      }

      await _iap!.restorePurchases();
      debugPrint('发起恢复购买请求');

      // 等待一段时间让恢复完成
      await Future.delayed(const Duration(seconds: 2));
      return true;
    } catch (e) {
      debugPrint('恢复购买失败: $e');
      return false;
    } finally {
      _isRestoring = false;
    }
  }

  /// 检查订阅状态
  Future<bool> checkSubscriptionStatus() async {
    try {
      final expiryDateStr = await HiveUtil.get<String>(
        'subscription',
        'expiry_date',
      );
      if (expiryDateStr == null) return false;

      final expiryDate = DateTime.parse(expiryDateStr);
      final now = DateTime.now();

      final isValid = now.isBefore(expiryDate);
      debugPrint('订阅状态检查: ${isValid ? "有效" : "已过期"}, 过期时间: $expiryDate');

      return isValid;
    } catch (e) {
      debugPrint('检查订阅状态失败: $e');
      return false;
    }
  }

  /// 获取产品列表
  List<ProductDetails> get products => _products;

  /// 获取订阅产品列表
  List<ProductDetails> get subscriptionProducts =>
      _products.where((p) => _subscriptionProductIds.contains(p.id)).toList();

  /// 获取非消耗品产品列表
  List<ProductDetails> get nonConsumableProducts =>
      _products.where((p) => _nonConsumableProductIds.contains(p.id)).toList();

  /// 获取消耗品产品列表
  List<ProductDetails> get consumableProducts =>
      _products.where((p) => _consumableProductIds.contains(p.id)).toList();

  /// 释放资源
  void dispose() {
    _subscription?.cancel();
    _subscription = null;
  }
}
